<template>
  <div class="app-container">
    <!--页头-->
    <div class="filter-container">
      <el-input
        :placeholder="'用户名'"
        v-model="listQuery.username_LIKE"
        style="width: 200px;"
        @keyup.enter.native="handleFilter"/>
      <el-input
        :placeholder="'邮箱'"
        v-model="listQuery.email_LIKE"
        style="width: 200px;"
        @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="reset" @click="resetCondition">
        <svg-icon icon-class="reset"/>
        重置
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="reset" @click="updatePwdHandler">
        <svg-icon icon-class="reset"/>
        重置密码
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate">添加
      </el-button>
      <el-button
        v-waves
        :loading="downloadLoading"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        @click="handleDelete">删除
      </el-button>
    </div>

    <!--table主体-->
    <el-table
      v-loading="listLoading"
      ref="table"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column width="33" type="selection" align="center"/>
      <el-table-column :label="'用户名'" align="center" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'邮箱'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'电话'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'状态'" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status==0?'禁用':'正常' }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="scope.row.username!=='admin'" type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页组件-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"/>

    <!--弹框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" style="margin-left:8px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username" clearable/>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogStatus==='create'">
          <el-input type="password" v-model="temp.password" style="width: 100%" show-password/>
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox-group v-model="checkRoles">
            <el-checkbox v-for="role in roles" :label="role.id" :key="role.id">{{role.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="12" :xs="24">
            <el-form-item label="手机号">
              <el-input v-model="temp.phone" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="邮箱">
              <el-input v-model="temp.email" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="12" :xs="24">
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="temp.status">
                <el-radio :label="0">禁用</el-radio>
                <el-radio :label="1">正常</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPwd">
      <el-input v-model="newPwd" :placeholder="'请输入新密码'" clearable/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPwd = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="updatePwd">{{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {add, fetchList, modify, remove, see,findRoles,updatePwd} from '@/api/user.js'
  import waves from '@/directive/waves'
  import Pagination from '@/components/Pagination'
  import AutoSelect from '@/components/AutoSelect'

  export default {
    name: 'ProductList',
    components: {Pagination, AutoSelect},
    directives: {waves},
    data() {
      return {
        updatePwdUserId: null,
        dialogPwd: false,
        newPwd: '', //新密码
        tableKey: 0,
        checkRoles:[],
        roles: [],  // 全部角色
        list: null, // 主体数据
        total: 0, // 总条数
        listLoading: true, // 是否加载中
        listQuery: { // 查询条件
          page: 1,
          limit: 10,
        },
        uploadUrl: process.env.BASE_API + '/file/upload',
        temp: {},
        dialogFormVisible: false,

        dialogStatus: '', // 当前弹窗
        textMap: { //  弹窗类型
          update: '修改用户',
          create: '添加用户'
        },
        rules: {
          username: [{required: true, message: '用户名不能为空', trigger: 'blur'}],
          password: [{required: true, message: '密码不能为空', trigger: 'blur'}],
          status: [{required: true, message: '请选择状态', trigger: 'blur'}],
        },
        downloadLoading: false
      }
    },
    created() {
      this.getList()
    },
    methods: {
      beforeUpload(file) {

      },
      uploadSuccess(res, file) {

      },
      // 重置搜索框
      resetCondition() {
        this.listQuery = { // 查询条件
          page: 1,
          limit: 10,
        }
        this.getList()
      },
      // 删除
      handleDelete() {
        var ids = ''
        this.$refs.table.selection.forEach(function (row) {
          if (ids !== '') {
            ids += ','
          }
          ids += row.id
        })
        if (ids === '') {
          this.$message({
            type: 'warning',
            message: '请选择要删除的数据!'
          })
          return
        }
        this.$confirm('删除后不可恢复，是否确认删除?', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          remove(ids).then((response) => {
            if (response.success) {
              this.getList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message.error('删除失败!')
            }
          })
        })
      },
      // 获得数据
      getList() {
        this.listLoading = true
        this.listQuery.username_NO_EQ = "admin"
        fetchList(this.listQuery).then(response => {
          this.list = response.rows
          this.total = response.total
          this.listLoading = false
        })
      },
      // 查询
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      // 创建页面
      handleCreate() {
        if(this.roles.length===0){
          findRoles().then(rep=>{
            if(rep.success) {
              this.roles = rep.data
            }
          })
        }
        this.temp.id = null
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      // 创建
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            var roles = this.checkRoles.join(",")
            this.checkRoles = []
            this.temp.roles = roles
            add(this.temp).then((response) => {
              if (response.success) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                })
                this.temp = {}
                this.dialogFormVisible = false
                this.getList()
              }
            })
          } else {
            console.log('验证不通过')
          }
        })
      },
      // 更新页面
      handleUpdate(row) {
        this.checkRoles = []
        if(this.roles.length===0){
          findRoles().then(rep=>{
            if(rep.success) {
              this.roles = rep.data
            }
          })
        }

        this.listLoading = true
        this.dialogStatus = 'update'

        see(row.id).then(response => {
          this.dialogFormVisible = true
          this.temp = response.data

          for (var i = 0; i < response.data.roleList.length; i++) {
            this.checkRoles.push(response.data.roleList[i].id)
          }

          this.listLoading = false
        })
      },
      // 更新数据
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            var roles = this.checkRoles.join(",")
            this.temp.roles = roles
            this.temp.roleList = null
            modify(this.temp).then((response) => {
              if (response.success) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
                this.dialogFormVisible = false
                this.getList()
              }
            })
          }
        })
      },
      updatePwdHandler(){
        if(this.$refs.table.selection.length<=0){
          this.$message.warning('请选择数据!')
          return
        }
        if(this.$refs.table.selection.length>1){
          this.$message.warning('只能选择一条数据!')
          return
        }
        this.updatePwdUserId = this.$refs.table.selection[0].id
        this.dialogPwd = true
      },
      // 更新密码
      updatePwd(){
        this.dialogPwd = false
        updatePwd({
          userId:this.updatePwdUserId,
          pwd:this.newPwd
        }).then(rep=>{
          if (rep.success) {
            this.$message({
              type: 'success',
              message: '重置成功!'
            })
          }
          this.newPwd=''
        })
      }
    }
  }
</script>
<style scoped>
  img {
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
  }
</style>
